package com.aaron.gesturehelper.gesturelib;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class MyInstanceLearner {
	private static final Comparator<MyPrediction> sComparator = new Comparator<MyPrediction>() {
        public int compare(MyPrediction object1, MyPrediction object2) {
            double score1 = object1.score;
            double score2 = object2.score;
            if (score1 > score2) {
                return -1;
            } else if (score1 < score2) {
                return 1;
            } else {
                return 0;
            }
        }
    };
    
    private final ArrayList<MyInstance> mInstances = new ArrayList<MyInstance>();

    /**
     * Add an instance to the learner
     * 
     * @param instance
     */
    void addInstance(MyInstance instance) { 
        mInstances.add(instance);
    }

    /**
     * Retrieve all the instances
     * 
     * @return instances
     */
    ArrayList<MyInstance> getInstances() {
        return mInstances;
    }

    /**
     * Remove an instance based on its id
     * 
     * @param id
     */
    void removeInstance(long id) {
    	int count = mInstances.size();
        for (int i = 0; i < count; i++) {
        	MyInstance instance = mInstances.get(i);
            if (id == instance.id) {
            	mInstances.remove(instance);
                return;
            }
        }
    }

    ArrayList<MyPrediction> classify(MyInstance instance) {
    	int type = instance.type;
    	
        ArrayList<MyPrediction> predictions = new ArrayList<MyPrediction>();
        int count = mInstances.size();
        
        for (int i = 0; i < count; i++) {
        	MyInstance sample = mInstances.get(i);
            if (sample.type != type) {
                continue;
            }
            double distance = sample.compareTwoInstance(instance);
            double weight;
            if (distance == 0) {
                weight = Double.MAX_VALUE;
            } else {
                weight = 1 / distance;
            }
            predictions.add(new MyPrediction(sample.label, weight));
        }

        Collections.sort(predictions, sComparator);

        return predictions;
    }
}
